#include <iostream>
#include <vector>
using namespace std;

struct ListNode
{
    int val;
    ListNode * next;
    ListNode() : val(0), next(nullptr)
    {}
    ListNode(int val) : val(val), next(nullptr)
    {}
    ListNode(int val, ListNode * next) : val(val), next(next)
    {}
};

class Solution 
{
public:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode * pre = nullptr;
        ListNode * cur = head;
        while(cur != nullptr)
        {
            ListNode * tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

// 辅助函数：根据数组创建链表
ListNode* createList(const vector<int>& nums) {
    ListNode dummy;
    ListNode* tail = &dummy;
    for (int num : nums) {
        tail->next = new ListNode(num);
        tail = tail->next;
    }
    return dummy.next;
}

// 辅助函数：打印链表
void printList(ListNode* head) {
    while (head) {
        cout << head->val;
        if (head->next) cout << "->";
        head = head->next;
    }
    cout << endl;
}

int main() {
    Solution sol;

    // 测试案例1
    vector<int> nums1 = {1, 2, 3, 4, 5};
    ListNode* head1 = createList(nums1);
    cout << "原链表1: ";
    printList(head1);
    ListNode* res1 = sol.reverseList(head1);
    cout << "反转后1: ";
    printList(res1);

    // 测试案例2
    vector<int> nums2 = {10, 20, 30};
    ListNode* head2 = createList(nums2);
    cout << "原链表2: ";
    printList(head2);
    ListNode* res2 = sol.reverseList(head2);
    cout << "反转后2: ";
    printList(res2);

    return 0;
}
